<template>
  <div>
    <div class="row-header">
      <el-form ref="searchForm" :model="searchForm" :inline="true" label-width="50px">
        <el-form-item label=" ">
          <el-date-picker
            v-model="startDate"
            class="select"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="充值开始日期"
            end-placeholder="充值结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @change="changeDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label=" ">
          <el-date-picker
            v-model="endDate"
            class="select"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="到账开始日期"
            end-placeholder="到账结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @change="changeDate1"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label=" ">
          <el-input v-model.trim="searchForm.opratorNumber" size="small" placeholder="请输入业务号码/ICCID" style="width: 350px"/>
        </el-form-item>
        <el-form-item label=" ">
          <el-input v-model.trim="searchForm.transactionId" size="small" placeholder="请输入交易流水号" style="width: 350px"/>
        </el-form-item>
        <el-form-item label=" ">
          <el-select v-model="searchForm.dictStatus" size="small" placeholder="请选择充值状态" style="width: 350px;" clearable>
            <el-option
              v-for="state in dictStatusSelect"
              :key="state.value"
              :label="state.label"
              :value="state.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="mini" icon="el-icon-search" @click="initData">查询</el-button>
        <el-button type="shenda" size="mini" icon="el-icon-refresh-right" @click="resetForm('searchForm')">重置</el-button>
        <el-button type="shenda" size="mini" icon="el-icon-download" @click="downloadData">导出数据</el-button>
      </div>
    </div>
    <div class="sd-page-line"/>
    <div class="row-main">
      <el-button type="shenda" size="mini"   @click="initData"  icon="el-icon-refresh">刷新数据</el-button>
      <div class='row-btn-block' v-has="'cardBalanceStatistics'">已充值余额总量: ￥{{allCardBalanceRecharge}}元</div>
      <div class='row-btn-block' v-has="'cardBalanceStatistics'">未使用余额总量: ￥{{sumCardBalance}}元</div>
      <el-table
        ref="table"
        :data="tableData"
        :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
        v-loading.fullscreen="mainTableLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        class="row-main-table"
      >
        <!-- <el-table-column type="checkbox" width="60" /> -->
        <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
        <el-table-column align="center" prop="cardNumber" label="业务号码"></el-table-column>
        <el-table-column align="center" prop="dictTransactionMothodName" label="交易途径"></el-table-column>
        <el-table-column align="center" prop="beforeRecharge" label="交易前金额"></el-table-column>
        <el-table-column align="center" prop="price" label="充值金额"></el-table-column>
        <el-table-column align="center" prop="afterRecharge" label="充值后金额"></el-table-column>
        <el-table-column align="center" prop="payAmount" label="支付金额"></el-table-column>
        <el-table-column align="center" prop="transactionId" label="交易流水号"></el-table-column>
        <el-table-column align="center" prop="dictStatusName" label="充值状态"></el-table-column>
        <el-table-column align="center" prop="insertTime" label="充值时间"></el-table-column>
        <el-table-column align="center" prop="updateTime" label="到账时间"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link"><svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon></span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button type="text" v-preventReClick @click="doRefund(scope.row)" v-has="'balanceRefundPer'" class="operation"
                             v-if="(scope.row.dictStatus==='USER_ORDER_HAVE_PAY'||scope.row.dictStatus==='USER_ORDER_REFUND')&&scope.row.transactionId">
                    退款
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" v-preventReClick @click="doRetry(scope.row)" v-has="'balanceRefundPer'" class="operation"
                             v-if="scope.row.dictStatus==='USER_ORDER_WAIT_PAY'">
                    重试
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.dictStatus=='USER_ORDER_WAIT_PAY'&&!scope.row.transactionId" v-has="'arriveRefundPer'">
                  <el-button type="text" v-preventReClick @click="doArrive(scope.row)"  class="operation" >
                    余额到账
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="text" v-preventReClick @click="updateTranId(scope.row)" class="operation">
                    修改支付流水号
                  </el-button>
                </el-dropdown-item>
<!--                <el-dropdown-item>-->
<!--                  <el-button type="text" v-preventReClick @click="refundDetail(scope.row)" v-if="scope.row.dictStatus==='USER_ORDER_REFUND'" v-has="'balanceRefundPer'"-->
<!--                  >退款详情-->
<!--                  </el-button>-->
<!--                </el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow':$store.state.app.screenWidth<992?'scroll':'auto'}">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="row-main-pager"
          :current-page.sync="current"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background></el-pagination>
      </div>
    </div>

    <!--申请退款-->
    <el-dialog title="退款详情" :visible.sync="showRefundApplyDialog" width="500px">
      <el-form :model="refundForm" ref="refundForm" :rules="refundRules" label-width='100px'>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="refundForm.refundAmount" autocomplete="off" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="退款余额" prop="refundBalance">
          <el-input v-model="refundForm.refundBalance" autocomplete="off" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            v-model="refundForm.cardIdremark"
            maxlength="100"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showRefundApplyDialog = false">取 消</el-button>
        <el-button type="primary" @click="doRefundOrder">确 定</el-button>
      </div>
    </el-dialog>
    <!--退款详情-->
<!--    <el-dialog title="退款详情" :visible.sync="showRefundTableDialog" width="50%">-->
<!--      <div style="max-height: 70vh;overflow: hidden;">-->
<!--        <el-table :data="refundList" :header-cell-style="{background: '#409EFF',color: '#fff'}">-->
<!--          <el-table-column type="index" label="序号" width="80"></el-table-column>-->
<!--          <el-table-column property="insertTime" label="申请时间" width="200"></el-table-column>-->
<!--          <el-table-column property="refundBalance" label="退款余额"></el-table-column>-->
<!--          <el-table-column property="refundAmount" label="退款金额"></el-table-column>-->
<!--          <el-table-column property="dictStatusName" label="退款状态"></el-table-column>-->
<!--          <el-table-column property="wxrefundId" label="退款流水号"></el-table-column>-->
<!--          <el-table-column property="remark" label="备注"></el-table-column>-->
<!--          <el-table-column property="empName" label="操作名称"></el-table-column>-->
<!--        </el-table>-->
<!--      </div>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="showRefundTableDialog = false">关 闭</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
    <!--  余额到账弹窗  -->
    <el-dialog title="余额到账" :visible.sync="showArriveDialog" width="30%" center>
      <div class="dialog-div">
        <div style="width: 130px;">交易流水号：</div>
        <div style="width: 80%"><el-input v-model="transactionId"  style="width: 100%"/></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitArrive" v-preventReClick>提 交</el-button>
      </div>
    </el-dialog>
    <!--  修改支付流水号弹窗  -->
    <el-dialog title="修改支付流水号" :visible.sync="showTransIdDialog" width="500px" center>
      <div class="dialog-div">
        <div style="width: 130px;">交易流水号：</div>
        <div style="width: 80%"><el-input v-model="transactionId"  style="width: 100%"/></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doUpdateTransId" v-preventReClick>提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {updateTransId,cardBalanceRecordsForPC, refundOrder, balanceRefundDetail,banlanceStatics,downloadCardBalanceList,cardBalanceUpdateTransId,balanceOrderRetry} from '@/api/getData'

  export default {
    name: 'BalanceOrder',
    data() {
      return {
        mainTableLoading: false,
        tableData: [],
        selectList: [],
        current: 1,
        pageSize: 10,
        total: 0,
        searchForm: {
          opratorNumber: '',
          dictStatus: '',
          startInsertTime: '',
          endInsertTime: '',
          startUpdateTime: '',
          endUpdateTime: '',
          transactionId:''
        },
        value: false,
        id: '',
        startDate: [],
        endDate: [],
        dictStatusSelect: [
          {
            value: '',
            label: '请选择充值状态'
          },
          {
            value: 'USER_ORDER_WAIT_PAY',
            label: '等待付款'
          },
          {
            value: 'USER_ORDER_HAVE_PAY',
            label: '充值成功'
          },
          {
            value: 'USER_ORDER_REFUND',
            label: '退款订单'
          } ,
          {
            value: 'USER_ORDER_BALANCE_REFUND',
            label: '预充充值套餐退款'
          }
        ],
        refundRules: {
          refundAmount: [
            {
              validator: (rule, value, callback) => {
                if (value == '') {
                  callback('请输入退款金额');
                  return
                }
                else {
                  let reg = /^[0-9]+(\.[0-9]{1,2})?$/;
                  if (reg.test(value)) {
                    callback();
                  }
                  else {
                    callback('退款金额格式错误');
                    return
                  }
                }
              }, tigger: 'input'
            }
          ],
          refundBalance: [
            {
              validator: (rule, value, callback) => {
                if (value == '') {
                  callback('请输入退款余额');
                  return
                }
                else {
                  let reg = /^[0-9]+(\.[0-9]{1,2})?$/;
                  if (reg.test(value)) {
                    callback();
                    return
                  }
                  else {
                    callback('退款余额格式错误');
                  }
                }
              }, tigger: 'input'
            }
          ],
        },
        showRefundApplyDialog: false,//弹窗
        showRefundTableDialog: false,//弹窗
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                picker.$emit('pick', [start, end])
              }
            }
          ]
        },
        refundForm: {
          cardId: '',
          cardBalanceId: '',//操作记录的id
          refundAmount: null,//退款金额
          refundBalance: null,//退款金额
          cardIdremark: '',//备注
        },
        refundList: [],
        sumCardBalance: null,
        allCardBalanceRecharge: null,
        pagekey: '',
        showArriveDialog: false,
        showTransIdDialog: false,
        transactionId: '',
        cardId: '',
        orderId: '',
        time: '',
      }
    },
    mounted() {
      const searchObj = sessionStorage.getItem(this.$route.path)
      if (searchObj != undefined && searchObj != null && searchObj != '') {
        this.searchForm = JSON.parse(searchObj)
        // console.log(this.searchForm);
        if (this.searchForm.startInsertTime !== '') {
          this.startDate.push(this.searchForm.startInsertTime)
        }
        if (this.searchForm.endInsertTime !== '') {
          this.startDate.push(this.searchForm.endInsertTime)
        }
        if (this.searchForm.startUpdateTime !== '') {
          this.endDate.push(this.searchForm.startUpdateTime)
        }
        if (this.searchForm.endUpdateTime !== '') {
          this.endDate.push(this.searchForm.endUpdateTime)
        }
      /*  if (this.searchForm.transactionId !== '') {
          this.transactionId.push(this.searchForm.transactionId)
        }*/
        //
        this.page = this.searchForm.page
      }
      this.initData();
      this.static()
    },
    methods: {
      downloadData(){
        let dictCardOperator = this.cardOperator === 'ALL' ? '' : this.cardOperator;
        downloadCardBalanceList(
          this.searchForm
        )
        this.$confirm('正在查询中，是否立即前往任务中心查看结果?', '提示', {
          confirmButtonText: '前往任务中心',
          cancelButtonText: '留在当前页',
          type: 'warning'
        }).then(() => {
          this.$router.push({
            path: '/mission/mission'
          })
        }).catch(() => {

        });
      },
      static(){
        banlanceStatics().then(res=>{
          this.sumCardBalance = res.data.sumCardBalance
          this.allCardBalanceRecharge = res.data.allCardBalanceRecharge
        })
      },
      //退款
      async doRefund(item) {
        this.pagekey = await this.$getPageKey();
        this.showRefundApplyDialog = true;
        this.refundForm = {
          cardId: item.cardId,
          cardBalanceId: item.id,//操作记录的id
          refundAmount: null,//退款金额
          refundBalance: null,//退款金额
          cardIdremark: '',//备注
        }
      },
      async doRetry(item){
        let pagekey = await this.$getPageKey();
        this.$confirm('是否继续重试当前余额订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await balanceOrderRetry({id:item.id,pagekey})
          if(res.data){
            this.$message({
              type: 'success',
              message: '余额订单重试提交成功!'
            });
            this.initData();
          }
          else{
            this.$message.error('余额订单重试失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重试'
          });
        });
      },
      //修改支付流水号
      async updateTranId(row){
        this.id = row.id;
        this.transactionId = row.transactionId;
        this.pagekey = await this.$getPageKey();
        this.showTransIdDialog = true;
      },
      doUpdateTransId(){
        this.$confirm('是否确认修改当前订单支付流水号?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(!this.transactionId){
            this.$message.error('请填写支付流水号');
            return false;
          }
          this.updateTransId()

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      async updateTransId(){
        let res = await updateTransId({id:this.id, transactionId: this.transactionId},{pagekey: this.pagekey})
        if(res.code==10000){
          this.$message({
            type: 'success',
            message: '订单支付流水号修改成功!'
          });
          this.showTransIdDialog = false;
          this.initData();
        }
      },
      //退款详情
      refundDetail(row) {
        this.showRefundTableDialog = true;
        balanceRefundDetail({
          cardBalanceId: row.id
        }).then(res=>{
          this.refundList = res.data.length>0?res.data:[];
        })
      },
      //提交退款订单
      doRefundOrder() {
        this.$refs.refundForm.validate((valid) => {
          if (valid) {
            let returnData = refundOrder({
              cardId: this.refundForm.cardId,
              cardBalanceId: this.refundForm.cardBalanceId,
              refundAmount: this.refundForm.refundAmount,
              refundBalance: this.refundForm.refundBalance,
              remark: this.refundForm.cardIdremark,
              pagekey:this.pagekey
            }).then(async res => {
              this.showRefundApplyDialog = false;
              this.pagekey = await this.$getPageKey();
              if (res.code === 10000) {
                this.$message({
                  type: 'success',
                  message: '退款成功~'
                });
                this.initData();
              }
            });
          } else {
            return false;
          }
        });

      },
      //点击行尾余额到账
      async doArrive(row){
        this.showArriveDialog = true;
        this.transactionId = '';
        this.time = row.insertTime;
        this.cardId = row.cardId;
        this.orderId = row.id;
        this.pagekey = await this.$getPageKey();
      },
      //提交交易流水号
      submitArrive(){
        if(this.transactionId==''){
          this.$message.error('请输入交易流水号');
          return false;
        }
        this.$confirm(`请参考当前订单创建时间:${this.time},确认交易流水号核对无误后点击确定`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await cardBalanceUpdateTransId({
            cardId: this.cardId,
            transactionId: this.transactionId,
            pagekey: this.pagekey,
            id: this.orderId,
          })
          if(res.code==10000){
            this.$message({
              type: 'success',
              message: '余额到账成功!'
            });
            this.showArriveDialog = false;
          }
          // this.doArriveOrder()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },

      // 数据初始化
      async initData() {
        this.searchForm.page = {
          current: this.current,
          size: this.pageSize
        };
        this.mainTableLoading = true;
        sessionStorage.setItem(this.$route.path, JSON.stringify(this.searchForm))

        const returnData = await cardBalanceRecordsForPC(this.searchForm,
          {
            obj: this,
            key: 'tableLoading'
          });
        this.tableData = [];
        this.total = 0;
        this.tableLoading = false;
        this.mainTableLoading = false;
        if (returnData._result&&returnData.data&&returnData.data.records) {
          this.total = returnData.data.total;
          const imageUrl = localStorage.getItem('image');
          returnData.data.records.map(item => {
            const obj = {};
            obj.id = item.id;
            obj.cardId = item.cardId;
            obj.cardNumber = item.cardNumber;
            obj.dictTransactionMothodName = item.dictTransactionMothodName; // 交易途径
            obj.beforeRecharge = item.beforeRecharge; // 交易前金额
            obj.price = item.price; // 充值金额
            obj.afterRecharge = item.afterRecharge; // 交易后金额
            obj.payAmount = item.payAmount; // 支付金额
            obj.transactionId = item.transactionId; // 交易流水号
            obj.dictStatus = item.dictStatus; // 充值状态
            obj.dictStatusName = item.dictStatusName; // 充值状态字典
            obj.insertTime = item.insertTime; // 申请时间
            obj.updateTime = item.updateTime; // 处理时间
            this.tableData.push(obj)
          });

        }
      },
      // 分页
      handleCurrentChange(val) {
        this.current = val;
        this.initData()
      },
      handleSizeChange(val){
        this.pageSize = val;
        this.current = 1;
        this.initData();
      },
      // 申请时间区间
      changeDate() {
        if (this.startDate) {
          this.searchForm.startInsertTime = this.startDate[0]
          this.searchForm.endInsertTime = this.startDate[1]
        } else {
          this.searchForm.startInsertTime = ''
          this.searchForm.endInsertTime = ''
        }
      },
      // 处理时间区间
      changeDate1() {
        // console.log(this.endDate);
        if (this.endDate) {
          this.searchForm.startUpdateTime = this.endDate[0]
          this.searchForm.endUpdateTime = this.endDate[1]
        } else {
          this.searchForm.startUpdateTime = ''
          this.searchForm.endUpdateTime = ''
        }
      },
      // 重置-查询条件
      resetForm(formName) {
        // this.$refs[formName].resetFields();
        this.startDate = ''
        this.endDate = ''
        this.searchForm = {
          operatorNumber: '',
          dictStatus: '',
          startInsertTime: '',
          endInsertTime: '',
          startUpdateTime: '',
          endUpdateTime: ''
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .row-btn-block{
    width: auto;
    height: 32px;
    position: relative;
    display: inline-block;
    float: right;
    border: 1px solid var(--lightBg) !important;
    color: var(--lightBg) !important;
    padding: 0 14px;
    border-radius: 20px;
    line-height: 32px;
    font-size: 12px;
  }

  .examine /deep/ .el-dialog__body {
    text-align: center;
    font-size: 14px;
    font-family: 微软雅黑;
    line-height: 40px;
    color: #606266;
    font-weight: 700;
  }

  .el-popper[x-placement^=bottom] {
    margin-right: -25px;
    box-shadow: 0px 0px 10px #888888;
    margin-left: 6px;

    .operation {
      border: 0;
      outline: none;
      display: block;
      text-align: center;
      margin: 0;
    }
  }

  .el-popper[x-placement^=top] {
    box-shadow: 0px 0px 10px #888888;
    margin-left: 6px;
    margin-right: -25px;

    button {
      display: block;
    }

    .operation {
      border: 0;
      outline: none;
      display: block;
      text-align: center;
      margin: 0;
    }
  }
  .dialog-div{
    width: 100%;
    height: 40px;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
